package com.ludomancy.hugealien;


import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;

import com.ludomancy.gamelib.Accumulator;
import com.ludomancy.gamelib.ImageManipulation;
import com.ludomancy.gamelib.Utils;
import com.ludomancy.gamelib.Widget;

public class MainWidget extends Widget
{
	private HelpWidget help;
	private Image backbuffer;
	private Graphics backG;
	
	private Accumulator instructions = new Accumulator(8000);
	
	public MainWidget(Widget parent, Rectangle area)
	{
		super(parent, area);
		backbuffer = ImageManipulation.createImage(area.width, area.height);
		backG = backbuffer.getGraphics();
	}
	
	public void mouseDown(Point pos)
	{
		Game.game.player.setCutMode(true);
	}
	
	public void mouseUp(Point pos)
	{
		Game.game.player.setCutMode(false);
	}
	
	public void update()
	{
		Game.game.update();
		instructions.update();
	}
	
	public void paint(Graphics g)
	{
		Game.game.city.paint(backG, null);
		
		if(!Game.game.isOver && instructions.isRunning())
		{
			backG.setColor(getTheme().getDefaultTextColor());
			backG.setFont(((GameTheme)getTheme()).ingame);
			Utils.drawMultiline(backG, "Press 'I' for help", getWidth()-6, 3, 3);
		}
		if(Game.game.isOver)
		{
			backG.setColor(getTheme().getDefaultTextColor());
			backG.setFont(((GameTheme)getTheme()).ingame);
			Utils.drawMultiline(backG, "The End ("+Game.game.player.finaleMessage+")", getWidth()-6, 3, 3);
		}
		
		g.drawImage(backbuffer, 0, 0, getWidth(), getHeight(), 0, 0 , getWidth()/2, getHeight()/2, null);
	}

	public void keyPressed(KeyEvent e)
	{
		processKey(e, true);
	}
	
	public void keyReleased(KeyEvent e)
	{
		processKey(e, false);
	}
	
	public static int debug = 0;
	private void processKey(KeyEvent e, boolean pressed)
	{
		if(!pressed)
			return;
		switch(e.getKeyCode())
		{
			case KeyEvent.VK_I:
				if(help == null)
					help = new HelpWidget(this, getClientRect());
				else
					help.leave();
				break;
			case KeyEvent.VK_R:
				if(help == null)
					HugeAlienApp.app.resetGame();
				break;
			// debug
			case KeyEvent.VK_0:
				debug++;
				break;
			case KeyEvent.VK_1:
				debug++;
				break;
			case KeyEvent.VK_2:
				debug--;
				break;
		}
	}
	
	public void mouseMoved(Point pos)
	{
		Game.game.player.x = pos.x/2;
		Game.game.player.y = pos.y/2;
	}
	
	public void onMouseExit()
	{
		Game.game.setPaused(true);
	}

	public void onMouseEntered()
	{
		Game.game.setPaused(false);
	}

	public void showGame()
	{
		help.close();
		help = null;
	}
}
